package com.yunkaweilai.android.activity.operation.consumption;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.TextView;

import com.classic.common.MultipleStatusView;
import com.github.lazylibrary.util.StringUtils;
import com.google.gson.Gson;
import com.yunkaweilai.android.R;
import com.yunkaweilai.android.activity.CaptureActivity;
import com.yunkaweilai.android.base.BaseActivity;
import com.yunkaweilai.android.base.BaseApplication;
import com.yunkaweilai.android.constants.Api;
import com.yunkaweilai.android.model.jici.CommonMemberModel;
import com.yunkaweilai.android.model.member.MemberHeadModel;
import com.yunkaweilai.android.model.member.MemberLevelModel;
import com.yunkaweilai.android.model.member.MemberListModel;
import com.yunkaweilai.android.net.HttpRequest;
import com.yunkaweilai.android.net.PostProcess;
import com.yunkaweilai.android.utils.InputMethodUtils;
import com.yunkaweilai.android.utils.TitleBuilder;
import com.yunkaweilai.android.utils.Utils;
import com.zhy.adapter.abslistview.CommonAdapter;
import com.zhy.adapter.abslistview.ViewHolder;
import com.zhy.m.permission.MPermissions;
import com.zhy.m.permission.PermissionDenied;
import com.zhy.m.permission.PermissionGrant;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.bingoogolapple.refreshlayout.BGARefreshLayout;

/**
 * 搜索会员
 * Created by Administrator on 2017/7/14.
 */

public class SearchMemberActivity extends BaseActivity implements BGARefreshLayout.BGARefreshLayoutDelegate, android.widget.RadioGroup.OnCheckedChangeListener {


    @BindView(R.id.id_edt_search)
    EditText idEdtSearch;
    @BindView(R.id.id_img_clean)
    ImageView idImgClean;
    @BindView(R.id.id_img_qr_code)
    ImageView idImgQrCode;
    @BindView(R.id.id_listView)
    ListView idListView;
    @BindView(R.id.content_view)
    BGARefreshLayout contentView;
    @BindView(R.id.id_multipleStatusView)
    MultipleStatusView idMultipleStatusView;
    @BindView(R.id.radiogroup_list)
    android.widget.RadioGroup RadioGroup;
    @BindView(R.id.radio_list_1)
    RadioButton RadioButton1;
    @BindView(R.id.radio_list_2)
    RadioButton RadioButton2;
    @BindView(R.id.radio_list_3)
    RadioButton RadioButton3;
    @BindView(R.id.radio_list_4)
    RadioButton RadioButton4;
    @BindView(R.id.radio_list_5)
    RadioButton RadioButton5;
    public static final String SEARCH_MEMBER_FLAG = "SEARCH_MEMBER_FLAG";//是否选中会员
    public static final String SEARCH_MEMBER_MODEL = "SEARCH_MEMBER_MODEL";
    public static final String SEARCH_MEMBER_BUNDLE = "SEARCH_MEMBER_BUNDLE";
    private boolean isRadioButton;
    private int mpage = 1;
    private int mpage1 = 1;
    private int select;
    private boolean mHasMore = true;
    private boolean isSearch = false;
    private String keywords = "";
    private ArrayList<MemberHeadModel> memberList = new ArrayList<>();
    private CommonAdapter<MemberHeadModel> adapter;
    private Gson gson = new Gson();
    private ArrayList<MemberLevelModel.DataBean.ListBean> list = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_jici_member);
        ButterKnife.bind(this);
        new TitleBuilder(mAc)
                .setLeftImage(R.mipmap.ic_go_back)
//                .setTitleText(getResources().getString(R.string.tab_main_2))
                .setTitleText("搜索会员")
                .setLeftOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent();
                        intent.putExtra(SEARCH_MEMBER_FLAG, false);
                        Bundle bundle = new Bundle();
                        bundle.putSerializable(SEARCH_MEMBER_MODEL, null);
                        intent.putExtra(SEARCH_MEMBER_BUNDLE, bundle);
                        setResult(RESULT_OK, intent);
                        finish();
                    }
                });
        initRefreshLayout(contentView, this, true);
        idMultipleStatusView.showLoading();
        idMultipleStatusView.setOnRetryClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                idMultipleStatusView.showLoading();
//                initHttp(true);
                initView();
            }
        });
        initAdapter();
        initView();
        initClick();
    }

    private void initView() {
        /**
         * 获取会员等级
         */
        HttpRequest.postUrl(Api.MEMBER_LEVEL_LIST)
                .execute(new PostProcess.StringCallBack() {
                    @Override
                    public void onResponse(String json) {
                        dismissProgressDialog();
                        boolean checkCode = Utils.checkCode(mAc, json);
                        if (checkCode) {
                            Gson gson = new Gson();
                            MemberLevelModel memberLevelModel = gson.fromJson(json, MemberLevelModel.class);
                            list.clear();
                            list.addAll(memberLevelModel.getData().getList());
                            if (list.size() != 0) {
                                RadioGroup.setVisibility(View.VISIBLE);
                                setRadioButtontext(list);
                                RadioGroup.setOnCheckedChangeListener(SearchMemberActivity.this);
                                RadioGroup.check(R.id.radio_list_1);
                            } else {
                                RadioGroup.setVisibility(View.GONE);
                                idMultipleStatusView.showEmpty();
                            }
                        }
                    }

                    @Override
                    public void onError(Exception e) {
                        dismissProgressDialog();
                    }
                });
    }

    private void setRadioButtontext(ArrayList<MemberLevelModel.DataBean.ListBean> list) {
        isRadioButton = true;
        switch (list.size()) {
            case 0:
                RadioButton1.setVisibility(View.VISIBLE);
                RadioButton2.setVisibility(View.GONE);
                RadioButton3.setVisibility(View.GONE);
                RadioButton4.setVisibility(View.GONE);
                RadioButton5.setVisibility(View.GONE);
                break;
            case 1:
                RadioButton1.setVisibility(View.VISIBLE);
                RadioButton2.setVisibility(View.VISIBLE);
                RadioButton3.setVisibility(View.GONE);
                RadioButton4.setVisibility(View.GONE);
                RadioButton5.setVisibility(View.GONE);
                RadioButton2.setText(this.list.get(0).getLevel_name());
                break;
            case 2:
                RadioButton1.setVisibility(View.VISIBLE);
                RadioButton2.setVisibility(View.VISIBLE);
                RadioButton3.setVisibility(View.VISIBLE);
                RadioButton4.setVisibility(View.GONE);
                RadioButton5.setVisibility(View.GONE);
                RadioButton2.setText(this.list.get(0).getLevel_name());
                RadioButton3.setText(this.list.get(1).getLevel_name());
                break;
            case 3:
                RadioButton1.setVisibility(View.VISIBLE);
                RadioButton2.setVisibility(View.VISIBLE);
                RadioButton3.setVisibility(View.VISIBLE);
                RadioButton4.setVisibility(View.VISIBLE);
                RadioButton5.setVisibility(View.GONE);
                RadioButton2.setText(this.list.get(0).getLevel_name());
                RadioButton3.setText(this.list.get(1).getLevel_name());
                RadioButton4.setText(this.list.get(2).getLevel_name());
                break;
            default:
                RadioButton1.setVisibility(View.VISIBLE);
                RadioButton2.setVisibility(View.VISIBLE);
                RadioButton3.setVisibility(View.VISIBLE);
                RadioButton4.setVisibility(View.VISIBLE);
                RadioButton5.setVisibility(View.VISIBLE);
                RadioButton2.setText(this.list.get(0).getLevel_name());
                RadioButton3.setText(this.list.get(1).getLevel_name());
                RadioButton4.setText(this.list.get(2).getLevel_name());
                RadioButton5.setText(this.list.get(3).getLevel_name());
                break;
        }
    }

    @Override
    public void onBackPressed() {
        // 双击返回键关闭程序
        Intent intent = new Intent();
        intent.putExtra(SEARCH_MEMBER_FLAG, false);
        Bundle bundle = new Bundle();
        bundle.putSerializable(SEARCH_MEMBER_MODEL, null);
        intent.putExtra(SEARCH_MEMBER_BUNDLE, bundle);
        setResult(RESULT_OK, intent);
        finish();
    }

    private void initClick() {
        idEdtSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if ((actionId == 0 || actionId == 3) && event != null && idEdtSearch.length() > 0) {
                    //点击搜索要做的操作
                    isSearch = true;
                    initHttp(true, idEdtSearch.getText().toString());
                    keywords = idEdtSearch.getText().toString();
                    InputMethodUtils.closeSoftKeyboard(mAc);
                }
                return false;
            }
        });

        idEdtSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s == null || s.length() == 0) {
                    idImgClean.setVisibility(View.GONE);
                    return;
                } else {
                    idImgClean.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        idListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                MemberHeadModel memberHeadModel = memberList.get(position);
                if ("2".equals(memberHeadModel.getMl_status())) {
                    showToast("会员已锁定");
                    return;
                } else if ("3".equals(memberHeadModel.getMl_status())) {
                    showToast("会员已挂失");
                    return;
                }
//                if (memberHeadModel.getStatus_info().is_valid()){
                if (memberHeadModel.getStatusStr().equals("过期")) {
                    showToast("会员已过期");
                    return;
                }
                Intent intent = new Intent();
                intent.putExtra(SEARCH_MEMBER_FLAG, true);
                Bundle bundle = new Bundle();
                bundle.putSerializable(SEARCH_MEMBER_MODEL, memberList.get(position));
                intent.putExtra(SEARCH_MEMBER_BUNDLE, bundle);
                setResult(RESULT_OK, intent);
                finish();
            }
        });
    }

    //radiobutton请求会员列表
    private boolean initHttp1(final boolean refresh, int selected) {
        mpage1 = refresh ? 1 : mpage1;
        if ((!mHasMore) && (!refresh)) {
            contentView.endLoadingMore();
            showToast("没有更多数据了");
            return false;
        }
        if (selected == 1) {
            HttpRequest.postUrl(Api.MEMBER_COMMON_LIST)
                    .addParams("ShowPage", "1")
                    .addParams("PageSize", "10")
                    .addParams("CurrPage", mpage1 + "")
                    .executeSearchMember(new PostProcess.StringCallBack() {
                        @Override
                        public void onResponse(String json) {
                            endRefreshOrLoad(refresh);
                            boolean checkCode = Utils.checkCode(mAc, json);
                            if (checkCode) {
                                mpage1++;
                                CommonMemberModel memberModel = gson.fromJson(json, CommonMemberModel.class);
                                if (refresh) {
                                    memberList.clear();
                                }
                                if (memberModel.getData().getPage().getCount().equals("0")) {
                                    idMultipleStatusView.showEmpty();
                                } else {
                                    idMultipleStatusView.showContent();
                                }
                                if (memberModel.getData().getList() != null && memberModel.getData().getList().size() > 0) {
                                    memberList.addAll(memberModel.getData().getList());
                                    mHasMore = memberModel.getData().getPage().isNext();//是否还有下一页
                                } else {
                                    showToast("没有数据");
                                }
                                adapter.notifyDataSetChanged();
                            } else {
                                idMultipleStatusView.showError();
                            }
                        }

                        @Override
                        public void onError(Exception e) {
                            idMultipleStatusView.showError();
                        }
                    });
        } else {
            HttpRequest.postUrl(Api.MEMBER_COMMON_LIST)
                    .addParams("ShowPage", "1")
                    .addParams("PageSize", "10")
                    .addParams("level_id", list.get(selected - 2).getId())
                    .addParams("CurrPage", mpage1 + "")
                    .addParams("searchtype", "senior")
                    .executeSearchMember(new PostProcess.StringCallBack() {
                        @Override
                        public void onResponse(String json) {
                            endRefreshOrLoad(refresh);
                            boolean checkCode = Utils.checkCode(mAc, json);
                            if (checkCode) {
                                mpage1++;
                                CommonMemberModel memberModel = gson.fromJson(json, CommonMemberModel.class);
                                if (refresh) {
                                    memberList.clear();
                                }
                                if (memberModel.getData().getPage().getCount().equals("0")) {
                                    idMultipleStatusView.showEmpty();
                                } else {
                                    idMultipleStatusView.showContent();
                                }
                                if (memberModel.getData().getList() != null && memberModel.getData().getList().size() > 0) {
                                    memberList.addAll(memberModel.getData().getList());
                                    mHasMore = memberModel.getData().getPage().isNext();//是否还有下一页
                                } else {
                                    showToast("没有数据");
                                }
                                adapter.notifyDataSetChanged();
                            } else {
                                idMultipleStatusView.showError();
                            }
                        }

                        @Override
                        public void onError(Exception e) {
                            idMultipleStatusView.showError();
                        }
                    });
        }


        return true;
    }

    //搜索
    private boolean initHttp(final boolean refresh, String keyword) {
        mpage = refresh ? 1 : mpage;
        if ((!mHasMore) && (!refresh)) {
            contentView.endLoadingMore();
            showToast("没有更多数据了");
            return false;
        }

        HttpRequest.postUrl(Api.MEMBER_COMMON_LIST)
                .addParams("ShowPage", "1")
                .addParams("PageSize", "10")
                .addParams("CurrPage", mpage + "")
                .addParams("keyword", keyword)
                .addParams("is_accurate_member", BaseApplication.getPayModel().getData().getInfo().getIs_accurate_member() ? "1" : "0")
                .executeSearchMember(new PostProcess.StringCallBack() {
                    @Override
                    public void onResponse(String json) {
                        endRefreshOrLoad(refresh);
                        boolean checkCode = Utils.checkCode(mAc, json);
                        if (checkCode) {
                            mpage++;
                            MemberListModel memberModel = gson.fromJson(json, MemberListModel.class);
                            if (refresh) {
                                memberList.clear();
                            }
                            if (memberModel.getData().getList() != null && memberModel.getData().getList().size() != 0) {
                                memberList.addAll(memberModel.getData().getList());
                                adapter.notifyDataSetChanged();
                                mHasMore = memberModel.getData().getPage().isNext();//是否还有下一页
                                if (idMultipleStatusView != null) {
                                    idMultipleStatusView.showContent();
                                }
                            } else {
                                mHasMore = false;
                                if (refresh) {
                                    if (idMultipleStatusView != null) {
                                        idMultipleStatusView.showEmpty();
                                    }
                                }
                            }
                        } else {
                            if (idMultipleStatusView != null) {
                                idMultipleStatusView.showError();
                            }
                        }
                    }

                    @Override
                    public void onError(Exception e) {
                        if (idMultipleStatusView != null) {
                            idMultipleStatusView.showError();
                        }
                    }
                });


        return true;

    }


    //会员列表正常
    private boolean initHttp(final boolean refresh) {
        mpage = refresh ? 1 : mpage;
        if ((!mHasMore) && (!refresh)) {
            contentView.endLoadingMore();
            showToast("没有更多数据了");
            return false;
        }
        HttpRequest.postUrl(Api.MEMBER_COMMON_LIST)
                .addParams("ShowPage", "1")
                .addParams("PageSize", "10")
                .addParams("CurrPage", mpage + "")
                .log(TAG)
                .executeSearchMember(new PostProcess.StringCallBack() {
                    @Override
                    public void onResponse(String json) {
                        endRefreshOrLoad(refresh);
                        Gson gson = new Gson();
                        boolean checkCode = Utils.checkCode(mAc, json);
                        if (checkCode) {
                            mpage++;
                            MemberListModel memberModel = gson.fromJson(json, MemberListModel.class);
                            if (refresh) {
                                memberList.clear();
                            }

                            if (memberModel.getData().getList() != null && memberModel.getData().getList().size() != 0) {
                                memberList.addAll(memberModel.getData().getList());
                                adapter.notifyDataSetChanged();
                                mHasMore = memberModel.getData().getPage().isNext();//是否还有下一页
                                if (idMultipleStatusView != null) {
                                    idMultipleStatusView.showContent();
                                }
                            } else {
                                mHasMore = false;
                                if (refresh) {
                                    if (idMultipleStatusView != null) {
                                        idMultipleStatusView.showEmpty();
                                    }
                                }
                            }
                        } else {
                            if (idMultipleStatusView != null) {
                                idMultipleStatusView.showError();
                            }
                        }
                    }

                    @Override
                    public void onError(Exception e) {
                        if (idMultipleStatusView != null) {
                            idMultipleStatusView.showError();
                        }
                    }
                });


        return true;
    }

    /**
     * 结束刷新组件
     *
     * @param refresh
     */
    private void endRefreshOrLoad(boolean refresh) {
        if (refresh) {
            if (contentView != null) {
                contentView.endRefreshing();
            }
        } else {
            if (contentView != null) {
                contentView.endLoadingMore();
            }
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case 111:
                    //处理扫描结果（在界面上显示）
                    if (null != data) {
                        Bundle bundle = data.getExtras();
                        if (bundle == null) {
                            return;
                        }
                        String result = bundle.getString(CaptureActivity.RESULT);
                        idEdtSearch.setText(result);
                        initHttp(true, result);

                    }
                    break;
            }
        }
    }

    private void initAdapter() {
        adapter = new CommonAdapter<MemberHeadModel>(mAc, R.layout.item_list_member, memberList) {
            @Override
            protected void convert(ViewHolder viewHolder, MemberHeadModel item, int position) {
                ImageView idImgHead = viewHolder.getView(R.id.id_img_head);

                Utils.MemberHeadImg(mAc, item.getMember_avatar(), item.getMember_sex(), idImgHead);
                TextView idTvName = viewHolder.getView(R.id.id_tv_name);
                //设置名字、手机和状态
                if (item.getStatusStr().equals("过期")) {
                    Utils.memberNameSet(item.getMember_name(), item.getMember_tel(), idTvName, "<font color='"+getResources().getColor(R.color.calu_red)+"'>" + "已过期" + "</font>");
                } else if ("2".equals(item.getMl_status())) {
                    Utils.memberNameSet(item.getMember_name(), item.getMember_tel(), idTvName, "<font color='"+getResources().getColor(R.color.calu_red)+"'>" + "已锁定" + "</font>");
                } else if ("3".equals(item.getMl_status())) {
                    Utils.memberNameSet(item.getMember_name(), item.getMember_tel(), idTvName, "<font color='"+getResources().getColor(R.color.calu_red)+"'>" + "已挂失" + "</font>");
                } else {
                    Utils.memberNameSet(item.getMember_name(), item.getMember_tel(), idTvName);
                }
                viewHolder.setText(R.id.id_tv_level, "等级：" + item.getLevel_name() + "     卡号：" + item.getCard_no());
                viewHolder.setText(R.id.id_tv_discount, "折扣：" + item.getDiscount() / 10 + "折   积分：" + item.getMember_points() + "   余额：" + item.getMember_price());
            }
        };
        idListView.setAdapter(adapter);

    }

    @OnClick({R.id.id_img_qr_code, R.id.id_img_clean})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.id_img_qr_code:
                getCameraManifest();
                break;
            case R.id.id_img_clean:
                idImgClean.setVisibility(View.GONE);
                idEdtSearch.setText("");
                keywords = "";
                memberList.clear();
                adapter.notifyDataSetChanged();
                if (isRadioButton) {
                    initHttp1(true, select);
                }
                break;
        }
    }


    public static final int SHOP_QR_CODE = 111;
    //获取照相机权限
    private static final int MY_PERMISSIONS_REQUEST_CAMERA = 1;

    private void getCameraManifest() {
        MPermissions.requestPermissions(this, MY_PERMISSIONS_REQUEST_CAMERA, Manifest.permission.CAMERA);
    }

    private void getCamera() {
        Intent intent = new Intent(mAc, CaptureActivity.class);
        startActivityForResult(intent, SHOP_QR_CODE);
    }

    @PermissionGrant(MY_PERMISSIONS_REQUEST_CAMERA)
    public void requestSuccess() {
        getCamera();
    }

    @PermissionDenied(MY_PERMISSIONS_REQUEST_CAMERA)
    public void requestError() {
        showToast("授权失败！");
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        MPermissions.onRequestPermissionsResult(this, requestCode, permissions, grantResults);
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

    }

    @Override
    public void onBGARefreshLayoutBeginRefreshing(BGARefreshLayout refreshLayout) {
        if (StringUtils.isEmpty(keywords)) {
            if (isRadioButton) {
                initHttp1(true, select);
            } else {
                initHttp(true, keywords);
            }
        } else {
            initHttp(true, keywords);
        }
    }

    @Override
    public boolean onBGARefreshLayoutBeginLoadingMore(BGARefreshLayout refreshLayout) {
        if (isRadioButton) {
            return initHttp1(false, select);
        } else return initHttp(false, keywords);
    }

    @Override
    public void onCheckedChanged(android.widget.RadioGroup group, int checkedId) {
        switch (checkedId) {
            case R.id.radio_list_1:
                select = 1;
                keywords = "";
                initHttp1(true, select);
                break;
            case R.id.radio_list_2:
                select = 2;
                keywords = "";
                initHttp1(true, select);
                break;
            case R.id.radio_list_3:
                select = 3;
                keywords = "";
                initHttp1(true, select);
                break;
            case R.id.radio_list_4:
                select = 4;
                keywords = "";
                initHttp1(true, select);
                break;
            case R.id.radio_list_5:
                select = 5;
                keywords = "";
                initHttp1(true, select);
                break;
        }
    }
}
